package cn.touna.jss.modules.third.jxl;

import cn.touna.risk.api.contraints.facet.First;
import cn.touna.risk.api.contraints.facet.Four;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.JuXinLiProperties;
import cn.touna.jss.common.util.HttpClientUtils;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.credit.service.AuthHistoryService;
import cn.touna.jss.modules.custom.auth.entity.AuthHistoryEntity;
import cn.touna.jss.modules.third.jxl.entity.JuXinLiRequestEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.cache.redis.RedisCache;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * 聚信立调用
 *
 * @author Administrator
 */
@Service
public class JuXinLiService {
    private static final Logger LOGGER = LogManager.getLogger(JuXinLiService.class);

    private static final String JUXINLI_TOKEN = "juxinli_token";
    private static final String JUXINLI_RESET_PASSWORD = "juxinli_reset_password";
    private Map<Thread, Response> threadResponseMap = new HashMap<>();

    @Autowired
    private JuXinLiProperties jxlProperties;

    @Autowired
    RedisCache redisCache;

    @Autowired
    AuthHistoryService authHistoryService;

    @Resource(name = "scheduledThredPool")
    private ScheduledExecutorService threadPool;

    /**
     * 聚信立报告查询
     *
     * @param requestEntity
     * @return
     * @throws Exception
     */
    @ApiMapping(value = "JuXinLi.getAccessReportData",desc = "聚信立.聚信立报告查询")
    public Response getAccessReportData(JuXinLiRequestEntity requestEntity) {
        LOGGER.info("REQ 【聚信立报告查询请求入参】,params：{}", requestEntity);
        Response<String> response = new Response<>();
        ValidUtil.checkRequestParams(requestEntity, First.class);
        try {
            List<AuthHistoryEntity>  list  =  authHistoryService.getJxlAuthHistory(requestEntity.getIdCard(),requestEntity.getMobile());
            if(CollectionUtils.isEmpty(list)){
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(), "请手机认证后,获取报告");
            }
            String result = getAccessReportData(requestEntity.getName(), requestEntity.getIdCard(), requestEntity.getMobile());
            JSONObject jsonObject = JSONObject.parseObject(result);
            String dataResult = (String) jsonObject.get("success");
            String msg = (String) jsonObject.get("note");
            if ("false".equals(dataResult)) {
                return recursiveGetResult(requestEntity);
//                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(), msg);
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, result);
        } catch (Exception e) {
            LOGGER.error("REE 【聚信立报告查询异常】,msg:{}", e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }


    public Response getAccessReportData_v2(JuXinLiRequestEntity requestEntity) {
        LOGGER.info("REQ 【聚信立报告查询请求入参】,params：{}", requestEntity);
        Response<String> response = new Response<>();
        ValidUtil.checkRequestParams(requestEntity, First.class);
        try {
            String result = getAccessReportData(requestEntity.getName(), requestEntity.getIdCard(), requestEntity.getMobile());
            JSONObject jsonObject = JSONObject.parseObject(result);
            String dataResult = (String) jsonObject.get("success");
            String msg = (String) jsonObject.get("note");
            if ("false".equals(dataResult)) {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(), msg);
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, result);
        } catch (Exception e) {
            LOGGER.error("REE 【聚信立报告查询异常】,msg:{}", e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }


    /**
     * 根据用户基本信息返回JSON分析数据
     *
     * @param requestEntity
     * @return
     * @throws Exception
     */
    public String getTokenInfo(JuXinLiRequestEntity requestEntity) throws Exception {
        String reqJson = assembleFethTokenJson(requestEntity);
        LOGGER.info("getTokenInfo req json：{}", reqJson);
        //token获取url
        String url = this.jxlProperties.getTounaCollectTokenUrl() + "/" + jxlProperties.getOrgName();
        String resultJson = HttpClientUtils.httpPost(url, reqJson);
        LOGGER.info("getTokenInfo 请求结果：{}", resultJson);
        return resultJson;
    }


    /**
     * 数据源采集请求
     *
     * @param jsonreq
     * @return
     * @throws Exception
     */
    public String dataGatherReq(String jsonreq) throws Exception {
        //token获取url
        String url = this.jxlProperties.getBaseUrl() + jxlProperties.getCollectReqUrl();
        String resultJson = HttpClientUtils.httpPost(url, jsonreq);
        LOGGER.info("dataGatherReq result json：{}", resultJson);
        return resultJson;
    }

    /**
     * 组装获取token信息
     *
     * @return
     */
    private String assembledataGather(String token, String website, JuXinLiRequestEntity requestEntity) {
        JSONObject dataGather = new JSONObject();
        dataGather.put("token", token);
        dataGather.put("account", requestEntity.getMobile());
        dataGather.put("password", requestEntity.getPassword());
        dataGather.put("website", website);
        return dataGather.toString();
    }


    /**
     * 组装获取token信息
     *
     * @return
     */
    private String assembleFethTokenJson(JuXinLiRequestEntity requestEntity) {
        JSONObject jso = new JSONObject();
        JSONObject basic_info = new JSONObject();
        basic_info.put("name", requestEntity.getName());
        basic_info.put("id_card_num", requestEntity.getIdCard());
        basic_info.put("cell_phone_num", requestEntity.getMobile());
        basic_info.put("home_addr", requestEntity.getHomeAddr());
        basic_info.put("work_tel", requestEntity.getWorkTel());
        basic_info.put("work_addr", requestEntity.getWorkAddr());
        basic_info.put("cell_phone_num2", requestEntity.getMobileBackup());
        jso.put("basic_info", basic_info);
        net.sf.json.JSONArray contacts = net.sf.json.JSONArray.fromObject(requestEntity.getContacts());
        if (contacts != null) {
            jso.put("contacts", contacts);
        }
        return jso.toString();
    }


    /**
     * 根据用户基本信息返回JSON分析数据
     *
     * @param name
     * @param idcard
     * @param phone
     * @return
     * @throws Exception
     */
    public String getAccessReportData(String name, String idcard, String phone) throws Exception {
        StringBuilder url = new StringBuilder(jxlProperties.getAccessReportDataUrl());
        url.append("?access_token=").append(getToken())
                .append("&name=").append(name).append("&phone=").append(phone).append("&client_secret=")
                .append(jxlProperties.getClientSecret()).append("&idcard=").append(idcard);
        String message = "get access report data ";
        String result = getData(url.toString(), message);
        LOGGER.info("{}的请求结果：{}", message, result);
        return result;
    }

    /**
     * 根据不用的url， 使用 get方法获取数据
     *
     * @param url
     * @param message
     * @return
     * @throws Exception
     */
    private String getData(String url, String message) throws Exception {
        //记录日志
        LOGGER.info(message + "请求为 : {}", url);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        String result = client.newCall(request).execute().body().string();
        LOGGER.info(message + "返回结果为: {}", result);
        return result;
    }


    /**
     * 获取Token
     *
     * @return
     */
    private String getToken() {
        String accessToken = "";
        // 获取安全凭证码
        try {
            String tokenRes = getAccessReportToken();
            accessToken = getAccessToken(tokenRes);
        } catch (Exception e) {
            LOGGER.error("获取安全凭证码失败异常：{}", e);
        }
        return accessToken;
    }

    /**
     * 获取token
     *
     * @param tokenMsg
     * @return
     */
    public String getAccessToken(String tokenMsg) {
        int begin = tokenMsg.indexOf("access_token");
        int end = tokenMsg.indexOf("note");
        String token = tokenMsg.substring(begin + 15, end - 3);
        LOGGER.info("AccessToken is: {}", token);
        return token;
    }


    /**
     * 权限分配类接口,获得安全凭证码
     *
     * @return
     * @throws Exception
     */
    private String getAccessReportToken() throws Exception {
        StringBuffer url = new StringBuffer(jxlProperties.getAccessTokenReportUrl());
        url.append("?client_secret=").append(jxlProperties.getClientSecret())
                .append("&hours=").append(jxlProperties.getHours()).append("&org_name=").append(jxlProperties.getOrgName()); //拼接url
        String message = "get access report token ";
        String result = getData(url.toString(), message);
        return result;
    }


    @ApiMapping(value = "JuXinLi.jxlAuth",desc = "聚信立.手机认证")
    public Response jxlAuth(JuXinLiRequestEntity requestEntity) {
        LOGGER.info("jxlAuth req entity：{}", requestEntity);
        Response<String> response = new Response<>();
        try {
            Response validResponse = ValidUtil.valid(requestEntity, Four.class);
            if (validResponse != null)
                return validResponse;
            //通过电话号码 到redis中取token信息
            if (requestEntity.getCaptcha() == null || "".equals(requestEntity.getCaptcha()) || !redisCache.exist(JUXINLI_TOKEN + "_" + requestEntity.getMobile())) {
                return getMsgAuthCode2(requestEntity);
            }
            String json = redisCache.get(JUXINLI_TOKEN + "_" + requestEntity.getMobile());
            LOGGER.info("jxlAuth  token info：{}", json);
            JSONObject dataGather = JSONObject.parseObject(json);
            dataGather.put("captcha", requestEntity.getCaptcha());
            //数据采集
            String url = jxlProperties.getBaseUrl() + jxlProperties.getCollectReqUrl();
            LOGGER.info("jxlAuth 数据采集 request json：{}", dataGather.toString());
            String resultJson = HttpClientUtils.httpPost(url, dataGather.toString());
            LOGGER.info("jxlAuth 数据采集 resultJson：{}", resultJson);
            JSONObject jsonObject = JSONObject.parseObject(resultJson);
            boolean success = (boolean) jsonObject.get("success");
            JSONObject data = (JSONObject) jsonObject.get("data");
            if (!success || data == null) {
                String errorMsg = (String) jsonObject.get("message");
                response.setMsg(errorMsg);
                response.setCode(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR.getErrorCode());
                if (data != null) {
                    response.setData(data.toString());
                }
                return response.fail(response);
            }
            Integer process_code = (Integer) data.get("process_code");
            if (process_code == 10002 || process_code == 10004 || process_code == 10006 || process_code == 10017 || process_code == 10018 || process_code == 10001) {
                String msg = (String) data.get("content");
                response.setMsg(msg);
                return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, data.toString());
            }

            if (process_code != 10008) {
                String errorMsg = (String) data.get("content");
                response.setMsg(errorMsg);
                response.setCode(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR.getErrorCode());
                if (data != null) {
                    response.setData(data.toString());
                }
                return response.fail(response);
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, data.toString());
        } catch (Exception e) {
            LOGGER.error("jxlAuth is exception:{}", e);
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR);
        }
    }


    private Response getMsgAuthCode2(JuXinLiRequestEntity requestEntity) throws Exception {
        Response response = new Response();
        //获取tokin信息
        String tokenInfo = getTokenInfo(requestEntity);
        LOGGER.info("getMsgAuthCode2 tokenInfo result json :{}", tokenInfo);
        if (tokenInfo == null) {
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, "获取token失败");
        }
        String token = "";
        String website = "";
        JSONObject jsonObject = JSONObject.parseObject(tokenInfo);
        boolean tokenResult = (boolean) jsonObject.get("success");
        JSONObject data = (JSONObject) jsonObject.get("data");
        if (tokenResult && data != null) {
            token = (String) data.get("token");
            JSONObject datasource = (JSONObject) data.get("datasource");
            website = (String) datasource.get("website");
        }
        if (!tokenResult || "".equals(token) || "".equals(website)) {
            String errorMsg = (String) jsonObject.get("message");
            LOGGER.info("getMsgAuthCode2 token info errorMsg :{}", errorMsg);
            response.setMsg(errorMsg);
            response.setCode(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR.getErrorCode());
            if (data != null) {
                response.setData(data.toString());
            }
            return response.fail(response);
        }
        //数据源采集调用
        String dataGatherJson = assembledataGather(token, website, requestEntity);
        String result = dataGatherReq(dataGatherJson);
        LOGGER.info("getMsgAuthCode2 数据源采集调用 result:{}", result);
        boolean dataResult = (boolean) JSONObject.parseObject(result).get("success");
        if (!dataResult) {
            String errorMsg = (String) jsonObject.get("message");
            response.setMsg(errorMsg);
            response.setCode(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR.getErrorCode());
            if (data != null) {
                response.setData(data.toString());
            }
            return response.fail(response);
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        data = (JSONObject) resultJson.get("data");
        Integer process_code = (Integer) data.get("process_code");
        //开始采集行为数据
        if (process_code == 10008) {
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, data.toString());
        }

        if (process_code == 10002 || process_code == 10004 || process_code == 10006 || process_code == 10017 || process_code == 10018 || process_code == 10001) {
            JSONObject reqMsgTpl = (JSONObject) data.get("req_msg_tpl");
            if (reqMsgTpl != null) {
                String type = (String) reqMsgTpl.get("type");
                JSONObject dataGather = JSONObject.parseObject(dataGatherJson);
                dataGather.put("type", type);
                //存储redis
                redisCache.set(JUXINLI_TOKEN + "_" + requestEntity.getMobile(), dataGather.toString(), jxlProperties.getTokenLoseTime());
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, data.toString());
        } else {
            String errorMsg = (String) data.get("content");
            LOGGER.info("getMsgAuthCode2 dataGatherReq result errorMsg :{}", errorMsg);
            response.setMsg(errorMsg);
            response.setCode(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR.getErrorCode());
            if (data != null) {
                response.setData(data.toString());
            }
            return response.fail(response);
        }
    }


    /**
     * 获取蜜罐指令牌子
     *
     * @param requestEntity
     * @return
     * @throws Exception
     */
    @ApiMapping(value = "JuXinLi.getMiguanData",desc = "聚信立.获取蜜罐数据")
    public Response getMiguanData(JuXinLiRequestEntity requestEntity) {
        LOGGER.info("REQ 【聚信立获取蜜罐指令牌子】getMiguanData-requestEntity：{}", requestEntity);
        Response<String> response = new Response<>();
        try {
            Response validResponse = ValidUtil.valid(requestEntity, Four.class);
            if (validResponse != null)
                return validResponse;
            StringBuffer tokenUrl = new StringBuffer();
            tokenUrl.append(jxlProperties.getMiguanTokenUrl()).append("?").append("client_secret=").append(jxlProperties.getClientSecret());
            tokenUrl.append("&account=").append(jxlProperties.getOrgName());
            LOGGER.info("REQ 【聚信立获取蜜罐指令牌子】req tokenurl：{}", tokenUrl.toString());
            String tokenResult = getData(tokenUrl.toString(), "聚信立获取蜜罐指令牌子");
            JSONObject jsonObject = JSONObject.parseObject(tokenResult);
            String code = jsonObject.getString("code");
            String msg = (String) jsonObject.get("message");
            String accessToken = jsonObject.getJSONObject("data").getString("access_token");
            if (!"MIGUAN_ACCESS_SUCCESS".equals(code)) {
                response.setMsg(msg);
                response.setCode(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode());
                response.setFlag("F");
                return response;
            }

            StringBuffer queryUrl = new StringBuffer();
            queryUrl.append(jxlProperties.getMiguanQueryurl()).append("?").append("client_secret=").append(jxlProperties.getClientSecret());
            queryUrl.append("&access_token=").append(accessToken).append("&version=").append(jxlProperties.getMiguanVersion());
            queryUrl.append("&name=").append(requestEntity.getName()).append("&id_card=").append(requestEntity.getIdCard()).append("&phone=").append(requestEntity.getMobile());
            LOGGER.info("REQ 【聚信立获取蜜罐指令牌子】req query url：{}", queryUrl.toString());
            String dataResult = getData(queryUrl.toString(), "聚信立获取蜜罐指令牌子");
            JSONObject json = JSONObject.parseObject(dataResult);
            code = json.getString("code");
            msg = json.getString("message");
            if (!"MIGUAN_SEARCH_SUCCESS".equals(code)) {
                response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(), msg);
                return response;
            }
            return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, dataResult);
        } catch (Exception e) {
            LOGGER.error("gws调用【聚信立获取蜜罐指令牌子】异常,getMiguanData", e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }


    /**
     * 密码重置
     *
     * @param requestEntity
     * @return
     * @throws Exception
     */
    @ApiMapping(value = "JuXinLi.reSetPassword",desc = "聚信立.重置密码")
    public Response reSetPassword(JuXinLiRequestEntity requestEntity) {
        LOGGER.info("REQ 【重置密码】reSetPassword-requestEntity：{}", requestEntity);
        Response<String> response = new Response<>();
        JSONObject token = null;
        try {
            Response validResponse = ValidUtil.valid(requestEntity, Four.class);
            if (validResponse != null)
                return validResponse;
            //如果缓存中无token，取token返回
            String json = redisCache.get(JUXINLI_RESET_PASSWORD + "_" + requestEntity.getMobile());
            if (json != null) {
                token = JSONObject.parseObject(json);
            } else {
                response = getToken(requestEntity);
                String flag = response.getFlag();
                if (!flag.equals("S")) {
                    return response;
                }
                token = JSONObject.parseObject(response.getData());
                //加入缓存之中
                redisCache.set(JUXINLI_RESET_PASSWORD + "_" + requestEntity.getMobile(), token.toString(), jxlProperties.getTokenLoseTime());
            }
            String url = jxlProperties.getResetQueryurl();
            token.put("account", requestEntity.getMobile());
            token.put("type", requestEntity.getType());
            String reset_pwd_method = token.getString("reset_pwd_method");
            String website = token.getString("website");
            if (StringUtils.isEmpty(requestEntity.getCaptcha())) {
                LOGGER.info("dataGatherReq req1 json：{}", token.toString());
                String resultJson = HttpClientUtils.httpPost(url, token.toString());
                LOGGER.info("dataGatherReq result1 json：{}", resultJson);
                JSONObject jsonObject = JSONObject.parseObject(resultJson);
                JSONObject data = jsonObject.getJSONObject("data");
                if (!jsonObject.getBoolean("success")) {
                    String msg = jsonObject.getString("message");
                    response.setMsg(msg);
                    return response.fail();
                }
                data.put("reset_pwd_method", reset_pwd_method);
                String msg = data.getString("content");
                int code = data.getIntValue("process_code");
                response.setMsg(msg);
                response.setData(data.toString());
                if (code != 10002) {
                    response.setCode(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR.getErrorCode());
                    response.setData(data.toString());
                    return response.fail();
                }
                return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC,data.toString());
            } else {
                if (StringUtils.isEmpty(requestEntity.getCaptcha())) {
                    response.setMsg("验证码不能为空");
                    return response.fail();
                }
                if (reset_pwd_method.equals("2")) {
                    if (StringUtils.isEmpty(requestEntity.getPassword())) {
                        response.setMsg("密码不能为空");
                        return response.fail();
                    }
                    if (website.equals("chinamobilebj")) {
                        if (requestEntity.getPassword().length() < 8 || requestEntity.getPassword().length() > 12) {
                            response.setMsg("北京地区号码密码长度为8-12位");
                            return response.fail();
                        }
                    }
                }
                token.put("captcha", requestEntity.getCaptcha());
                token.put("password", requestEntity.getPassword());
                LOGGER.info("dataGatherReq req2 json：{}", token.toString());
                String resultJson = HttpClientUtils.httpPost(url, token.toString());
                LOGGER.info("dataGatherReq result2 json：{}", resultJson);
                JSONObject jsonObject = JSONObject.parseObject(resultJson);
                JSONObject data = jsonObject.getJSONObject("data");
                String msg = data.getString("content");
                int code = data.getIntValue("process_code");
                response.setMsg(msg);
                response.setData(data.toString());
                if (code == 10002) {
                    return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC,data.toString());
                }
                if (code != 11000) {
                    return response.fail();
                }
                token.remove("captcha");
                token.remove("password");
                return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC,data.toString());
            }
        } catch (Exception e) {
            LOGGER.error("调用【聚信立重置密码】异常,reSetPassword", e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }


    private Response getToken(JuXinLiRequestEntity requestEntity) {
        Response<String> response = new Response<>();
        String url = jxlProperties.getResetTokenUrl() + "/" + jxlProperties.getOrgName();
        JSONObject json = new JSONObject();
        JSONObject basic = new JSONObject();
        basic.put("name", requestEntity.getName());
        basic.put("id_card_num", requestEntity.getIdCard());
        basic.put("cell_phone_num", requestEntity.getMobile());
        json.put("basic_info", basic);
        String resultJson = HttpClientUtils.httpPost(url, json.toString());
        LOGGER.info("dataGatherReq result json：{}", resultJson);
        JSONObject tokenJson = JSONObject.parseObject(resultJson);
        String code = tokenJson.getString("code");
        String msg = tokenJson.getString("message");
        if (!code.equals("65557")) {
            response.setMsg(msg);
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL);
        }
        JSONObject data = tokenJson.getJSONObject("data");
        //0不支持重置，1代表短信验证码重置方式，2代表短信验证码+新密码重置方式
        String reset_pwd_method = data.getJSONObject("datasource").getString("reset_pwd_method");
        if (reset_pwd_method.equals("0")) {
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(),"不支持重置");
        }
        String token = data.getString("token");
        String website = data.getJSONObject("datasource").getString("website");

        JSONObject tokenInfo = new JSONObject();
        tokenInfo.put("token", token);
        tokenInfo.put("website", website);
        tokenInfo.put("reset_pwd_method", reset_pwd_method);
        response.setData(tokenInfo.toString());
        return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC);
    }





    /**
     * 定时刷新获取异步请求的结果
     *
     * @return
     */
    private Response recursiveGetResult(JuXinLiRequestEntity requestEntity) {
        long start = System.currentTimeMillis();
        Response response =  new Response();
        try {
            String result = getAccessReportData(requestEntity.getName(), requestEntity.getIdCard(), requestEntity.getMobile());
            JSONObject jsonObject = JSONObject.parseObject(result);
            String dataResult = (String) jsonObject.get("success");
            String msg = (String) jsonObject.get("note");
            CountDownLatch latch = new CountDownLatch(1);
            if (!"false".equals(dataResult)) {
                return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, result);
            }else {
                RequestResultThread requestResultThread = new RequestResultThread(requestEntity, Thread.currentThread(), threadResponseMap, latch);
                threadPool.execute(requestResultThread);
                try {
                    latch.await();
                    synchronized (threadResponseMap) {
                        response = threadResponseMap.get(Thread.currentThread());
                        threadResponseMap.remove(Thread.currentThread());
                        return response;
                    }
                } catch (Exception e) {
                    LOGGER.error("重新请求聚信立报告数据失败", e);
                    return ResponseFactory.fail(SystemErrorCodeEnum.CRS_SYSTEM_FAILED, e.getMessage());
                }
            }
        } catch (Exception e) {
            LOGGER.error("重新请求聚信立报告数据结果失败", e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        } finally {
            long cost = System.currentTimeMillis() - start;
            LOGGER.info("重新请求聚信立报告数据 手机号:{},身份证:{},消耗时间：" ,requestEntity.getMobile(),requestEntity.getIdCard(),cost);
        }
    }

    class RequestResultThread implements Runnable {

        private JuXinLiRequestEntity requestEntity;
        private Thread rootThread;
        private Map<Thread, Response> map;
        private CountDownLatch latch;
        private int count = 1;

        public RequestResultThread(JuXinLiRequestEntity requestEntity, Thread rootThread, Map<Thread, Response> map, CountDownLatch latch) {
            this.requestEntity = requestEntity;
            this.rootThread = rootThread;
            this.map = map;
            this.latch = latch;
        }

        @Override
        public void run() {
            Response response = new Response();
            try {
                 String result = getAccessReportData(requestEntity.getName(), requestEntity.getIdCard(), requestEntity.getMobile());
                LOGGER.info("重新请求聚信立报告数据，第" +count + "次，thread=" + Thread.currentThread().getName()+"返回结果"+result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String dataResult = (String) jsonObject.get("success");
                String msg = (String) jsonObject.get("note");
                if (!"false".equals(dataResult)) {
                    map.put(rootThread, response);
                    LOGGER.info("请求成功,停止执行");
                    latch.countDown();
                }
                else if (count++>4) {
                    response = ResponseFactory.fail(SystemErrorCodeEnum.CRS_TRY_FAILED, msg);
                    map.put(rootThread, response);
                    LOGGER.info("请求5次失败,停止执行");
                    latch.countDown();
                    LOGGER.info("请求5次失败,停止执行countDown");
                } else {
                    threadPool.schedule(this, 30, TimeUnit.SECONDS);
                }
            } catch (Exception e) {
                LOGGER.error("重新请求聚信立报告数据异常", e);
                response = ResponseFactory.fail(SystemErrorCodeEnum.CRS_SYSTEM_FAILED, e.getMessage());
                map.put(rootThread, response);
                latch.countDown();
            }
        }
    }










}
